package com.rabbitmq.demo;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

/**
 * @ClassName UserA
 * @Description 用户A（消费者A）
 * @Author Kx
 * @Date 2025/10/10 19:37
 * @Version 1.0
 */
public class UserA {
    /**
     * 定义体育队列
     */
    private static final String QUEUE_NAME = "queue.sports";

    /**
     * 定义交换机名称
    */
    private static final String EXCHANGE_NAME = "channel.direct";

    /**
     * 定义工厂
     */
    private static ConnectionFactory connectionFactory;

    static {
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("kx");
        connectionFactory.setPassword("123456");
    }

    /**
     * @author: kx
     * @date: 2025/10/10 19:43
     * @description: 接收消息
    */
    public static void receive() {
        try {
            // 创建连接
            Connection connection = connectionFactory.newConnection();
            // 创建通信
            Channel channel = connection.createChannel();

            // 声明交换机及其类型
            channel.exchangeDeclare(QUEUE_NAME, "direct");

            // 声明队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            // 绑定队列和交换机
            channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "sports.key");

            // 接收消息
            DeliverCallback callback = (consumerTag, delivery) -> {
                // 获取消息（消息队列中的内容是字节数组，因此转换为 String）
                String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
                System.out.println("用户A 接收到" + message + "消息");
            };

            // 订阅消息
            channel.basicConsume(QUEUE_NAME, true, callback, consumerTage->{});
        } catch (Exception e) {
            throw new RuntimeException("消费失败" + e);
        }
    }

    public static void main(String[] args) {
        receive();
    }
}
